package com.sita.redsun.connector.session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

public class SessionMap {

    private Logger logger = LoggerFactory.getLogger(SessionMap.class);
    private static SessionMap instance = new SessionMap();

    private ConcurrentHashMap<String, SunSession> map = new ConcurrentHashMap<String, SunSession>();
    private AtomicInteger sessionCount = new AtomicInteger(0);

    public static SessionMap sharedInstance() {
        return instance;
    }

    public void addSession(String uniqueId, SunSession session) {
        if (!map.containsKey(uniqueId)) {
            sessionCount.incrementAndGet();
        }
        map.put(uniqueId, session);
        logger.debug("SESSION_ADD " + uniqueId);
    }

    public void reset(){
        map.clear();
        sessionCount.set(0);
    }

    public SunSession getSession(String uniqueId) {
        return map.get(uniqueId);
    }

    public void removeSession(String uniqueId) {
        if (!map.containsKey(uniqueId)) {
            return;
        }
        map.remove(uniqueId);
        sessionCount.getAndDecrement();
        logger.debug("SESSION_REMOVED " + uniqueId);
    }

    public int getLiveSessionCount(){
        return sessionCount.get();
    }

  /*  public Map<String, SessionModel> getLiveSessions() {
        Collection<SunSession> sessions = map.values();
        Map<String, SessionModel> sessionModelMap = Maps.newHashMap();
        if (sessions != null && !sessions.isEmpty()){
            for (SunSession session : sessions){
                SessionModel sm = new SessionModel()
                        .setTerminalId(session.getSessionUniqueId())
                        .setHost(session.getHost())
                        .setPort(session.getPort())
                        .setLastActiveTime(session.getLastActiveTime());
                sessionModelMap.put(session.getSessionUniqueId(), sm);
            }
        }

        return sessionModelMap;
    }*/
}
